package com.example.test.advice.第七章_泛型和反射.建议107_使用反射增加装饰模式的普适性;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;

public class DecorateAnimal implements Animal{

    Animal animal;

    //使用哪一个包装器
    Class<? extends Feature> cls;

    public DecorateAnimal(Animal animal, Class<? extends Feature> cls) {
        this.animal = animal;
        this.cls = cls;
    }

    @Override
    public void doStuff() {
        InvocationHandler invocationHandler = (proxy, method, args) -> {
            Object obj =null;
            //设置包装条件
            if(Modifier.isPublic(method.getModifiers())){
                obj = method.invoke(cls.newInstance(),args);
            }
            animal.doStuff();
            return obj;
        };
        ClassLoader cl = cls.getClassLoader();
        Feature feature = (Feature) Proxy.newProxyInstance(cl, cls.getInterfaces(),invocationHandler);
        feature.load();
    }
}
